
package com.netease.xone.fragment;

import protocol.XoneCallBack;
import protocol.XoneService;
import protocol.meta.Source;
import protocol.meta.Subject;

import com.netease.xone.R;
import com.netease.xone.activity.ActivitySubjectDetail;
import com.netease.xone.adapter.HotSubjectListAdapter;
import com.netease.xone.view.HoriScrollSourceView;
import com.netease.xone.widget.SubjectBannerView;
import com.netease.xone.widget.listview.LoadingListView;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class FragmentRecommdation extends FragmentBase {

    public static FragmentRecommdation newInstance() {
        FragmentRecommdation fragment = new FragmentRecommdation();
        return fragment;
    }

    // View
    private SubjectBannerView mBanner;
    private HoriScrollSourceView mHoriSourceView;
    private LoadingListView mListView;
    private HotSubjectListAdapter mAdapter;
    // TransactionId
    private int mHotSubjectTid;
    private int mLatestSourceTid;
    private int mRecommdationSubjectTid;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        XoneService.getInstance().addListener(mCallBack);
        View v = inflater.inflate(R.layout.fragment_recommdation, null);
        mBanner = (SubjectBannerView)inflater.inflate(R.layout.view_recomm_banner, null);
        mHoriSourceView = (HoriScrollSourceView)inflater.inflate(
                R.layout.view_recomm_horiscroll_source, null);
        mListView = (LoadingListView)v.findViewById(R.id.recomm_list);
        mAdapter = new HotSubjectListAdapter(getActivity());
        renderView(v);
        return v;
    }

    private void renderView(View v) {
        mBanner.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
                Subject subject = mBanner.getItem(position);
                ActivitySubjectDetail.startActivity(getActivity(), subject.subjectId,
                        subject.subjectName);
            }
        });

        mListView.getRefreshableView().setHeaderDividersEnabled(true);
        mListView.getRefreshableView().addHeaderView(mBanner);

        RelativeLayout titleNewestSource = (RelativeLayout)View.inflate(getActivity(),
                R.layout.view_pgrecomm_divider_title, null);
        ((TextView)titleNewestSource.getChildAt(0)).setText(R.string.newest_source);

        mListView.getRefreshableView().addHeaderView(titleNewestSource);
        mListView.getRefreshableView().addHeaderView(mHoriSourceView);

        RelativeLayout titleHotSubject = (RelativeLayout)View.inflate(getActivity(),
                R.layout.view_pgrecomm_divider_title, null);
        ((TextView)titleHotSubject.getChildAt(0)).setText(R.string.hot_subject);

        mListView.getRefreshableView().addHeaderView(titleHotSubject);

        mHotSubjectTid = XoneService.getInstance().doGetHotestSubjectList();
        mLatestSourceTid = XoneService.getInstance().doGetLatestSourceList();
        mRecommdationSubjectTid = XoneService.getInstance().doGetRecommendSubjectList();

        mListView.setAdapter(mAdapter);
        mListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
                Subject subject = mAdapter.getItem(position
                        - mListView.getRefreshableView().getHeaderViewsCount());
                // XoneService.getInstance().doGetSubjectDetail(subject.subjectId,
                // null);
                if (subject != null) {
                    ActivitySubjectDetail.startActivity(getActivity(), subject.subjectId,
                            subject.subjectName);
                }
            }
        });
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (null != savedInstanceState) {
            int firstItem = savedInstanceState.getInt("firstitem");
            int firstItemTop = savedInstanceState.getInt("firstItemtop");
            mListView.getRefreshableView().setSelectionFromTop(firstItem, firstItemTop);

            int position = savedInstanceState.getInt("position");
            mBanner.setPosition(position);
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        if (null != mListView) {
            int firstItem = mListView.getRefreshableView().getFirstVisiblePosition();
            if (null != mListView.getChildAt(0)) {
                int firstItemTop = mListView.getChildAt(0).getTop();
                outState.putInt("firstitem", firstItem);
                outState.putInt("firstItemtop", firstItemTop);
            }
        }

        if (null != mBanner) {
            int position = mBanner.getPosition();
            outState.putInt("position", position);
        }

        super.onSaveInstanceState(outState);
    }

    @Override
    public void onDestroyView() {
        mHoriSourceView.removeListener();
        XoneService.getInstance().removeListener(mCallBack);
        if (null != mBanner) {
            mBanner.clear();
        }
        mBanner = null;
        mListView = null;
        super.onDestroyView();
    }

    private XoneCallBack mCallBack = new XoneCallBack() {

        @Override
        public void onGetHotestSubjectList(int trasactionId,
                java.util.List<protocol.meta.Subject> subjectList) {
            if (mHotSubjectTid == trasactionId) {
                mAdapter.addTail(subjectList);
            }
        };

        @Override
        public void onGetHotestSubjectListError(int transactionId, int errCode, String err) {
            // TODO
        };

        @Override
        public void onGetLatestSourceList(int trasactionId,
                java.util.List<protocol.meta.Source> sourceList) {
            if (mLatestSourceTid == trasactionId) {
                mHoriSourceView.setSources(sourceList);
            }
        };

        @Override
        public void onGetLatestSourceListError(int transactionId, int errCode, String err) {
            // TODO
        };

        @Override
        public void onGetRecommedSubjectList(int transactionId,
                java.util.List<protocol.meta.Subject> subjectList) {
            if (mRecommdationSubjectTid == transactionId) {
                mBanner.setData(subjectList);
            }
        };

        @Override
        public void onGetRecommedSubjectListError(int transactionId, int errCode, String err) {
            // TODO
        };

        @Override
        public void onSubscribe(int transactionId, int[] subjectIdAndSourceId) {
            if (mAdapter == null)
                return;
            // 有订阅信息，需要更新订阅状态
            int subjectId = subjectIdAndSourceId[0];
            int sourceId = subjectIdAndSourceId[1];
            // 更新订阅状态//TODO这里咱叔更新不了，因为这里的Subject没有带SourceList，没办法订阅的源属于哪个主题
            for (int i = 0; i < mAdapter.getCount(); i++) {
                Subject subject = mAdapter.getItem(i);
                if (subject.sourceList == null || subject.sourceList.size() == 0)
                    continue;// 忽略没有资讯源的主题
                if (subjectId > 0) {
                    // subjectId > 0,表明是订阅全部
                    if (subjectId == subject.subjectId) {
                        // 更新该主题下的所有资讯源
                        for (Source source : subject.sourceList) {
                            source.isSubscribed = true;
                            source.subscribeCount++;
                            subject.subscribeCount++;
                            subject.mySubCount++;
                        }
                        mAdapter.notifyDataSetChanged();
                        break;// 找到之后就没必要继续查找了
                    }
                } else {
                    // 订阅单个资讯源
                    for (Source source : subject.sourceList) {
                        if (sourceId == source.sourceId) {
                            // 更新该资讯源
                            source.isSubscribed = true;
                            source.subscribeCount++;
                            subject.mySubCount++;
                            subject.subscribeCount++;
                            mAdapter.notifyDataSetChanged();
                            break;// 找到之后就没必要继续查找了
                        }
                    }
                }
            }
        };

        @Override
        public void onUnsubscribe(int transactionId, int sourceId) {
            if (mAdapter == null)
                return;
            // 更新订阅状态//TODO这里咱叔更新不了，因为这里的Subject没有带SourceList，没办法订阅的源属于哪个主题
            for (int i = 0; i < mAdapter.getCount(); i++) {
                Subject subject = mAdapter.getItem(i);
                if (subject.sourceList == null || subject.sourceList.size() == 0)
                    continue;// 忽略没有资讯源的主题
                // 订阅单个资讯源
                for (Source source : subject.sourceList) {
                    if (sourceId == source.sourceId) {
                        // 更新该资讯源
                        source.isSubscribed = false;
                        source.subscribeCount--;
                        subject.mySubCount--;
                        subject.subscribeCount--;
                        mAdapter.notifyDataSetChanged();
                        break;// 找到之后就没必要继续查找了
                    }
                }
            }
        };
    };
}
